package com.jin.notifyserver;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.google.gson.Gson;
import com.jin.mqtt.MQTTManager;
import com.jin.mqtt.NetworkStateMonitor;
import com.jin.mqtt.NetworkUtils;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class MQTTService extends Service implements MQTTManager.OnMqttStatusListener {

    private static final String TAG = "MQTTService";
    private NetworkStateMonitor networkMonitor;
    private static final String CHANNEL_ID = "mqtt_channel";
    private CommandRepository commandRepository;

    @SuppressLint("ForegroundServiceType")
    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        startForeground(1, createNotification("OKX", "正在运行中..."));
        commandRepository = CommandRepository.getInstance();

        try {
            String url = "tcp://mqtt.xn--fjqr3ma.shop:1883";
            // 检查网络并连接 MQTT
            if (NetworkUtils.isNetworkConnected(this)) {
                MQTTManager.INSTANCE.connect(
                        "clientId123",
                        url,
                        "admin",
                        "123456"
                );
            } else {
                Log.e(TAG, "onCreate: ");
            }

            // 注册网络变化监听器
            networkMonitor = new NetworkStateMonitor(this, new NetworkStateMonitor.NetworkStateListener() {
                @Override
                public void onConnected() {
                    String url = "tcp://mqtt.xn--fjqr3ma.shop:1883";
                    MQTTManager.INSTANCE.connect(
                            "clientId123",
                            url,
                            "admin",
                            "123456"
                    );
                    MQTTManager.INSTANCE.setOnMqttStatusListener(MQTTService.this);
                }

                @Override
                public void onDisconnected() {
//                    MQTTManager.INSTANCE.disconnect();
                }
            });

            networkMonitor.register();

        } catch (Exception e) {
            Log.e(TAG, "onCreate: ", e);
        }
    }


    private Notification createNotification(String title, String text) {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .build();
    }

    private void showNotification(String title, String message) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.stat_notify_chat)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .setAutoCancel(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL);

        manager.notify((int) System.currentTimeMillis(), builder.build());
    }

    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(
                CHANNEL_ID,
                "OKX通知",
                NotificationManager.IMPORTANCE_HIGH
        );

        // 声音 + 震动
        AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();
        channel.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notification), audioAttributes);
        channel.enableVibration(true);
        channel.setVibrationPattern(new long[]{0, 200, 100, 300});
        channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        if (networkMonitor != null) {
            networkMonitor.unregister();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onConnectStatus(boolean status, String token) {
        Log.d(TAG, "onConnectStatus: "+status);
        MQTTManager.INSTANCE.subscribe("vm/AAAAAAAA/okx");
    }

    @Override
    public void onDisconnect() {
        Log.d(TAG, "onDisconnect: ");
    }

    @Override
    public void onMessageArrived(String topic, MqttMessage message) {
        Log.d(TAG, "onMessageArrived: "+topic+":"+message.toString());
        String content = message == null ? null : message.toString();

        if (content == null || content.isEmpty()) {
            return;
        }
        OkxDto okxDto = new Gson().fromJson(content, OkxDto.class);
        commandRepository.okx(okxDto);
        showNotification("OKX", okxDto.getData().getContent());

    }

    @Override
    public void onDeliveryComplete(String token) {
        Log.d(TAG, "onDeliveryComplete: ");
    }

    @Override
    public void onConnectionLost(String cause) {
        Log.d(TAG, "onConnectionLost: ");
    }

    @Override
    public void onSubscribeStatus(boolean status, String topic) {
        Log.d(TAG, "onSubscribeStatus: ");
    }

    @Override
    public void onPublishStatus(String status, String topic) {
        Log.d(TAG, "onPublishStatus: ");
    }
}